package org.java;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class DoJoin {

	//1万条以内,插入ArrayList,直接用ArrayList进行Join
	public static ArrayList<?> MinJoin(ArrayList<?> objList1, ArrayList<?> objList2) {	
		if (objList1.size() < objList2.size()) {
			objList1.retainAll(objList2);
			return objList1;
		} else {
			objList2.retainAll(objList1);
			return objList2;
		}
	}		
	
	//10万条以内,插入HashSet,直接用HashSet进行Join
	public static HashSet<?> MidJoin(HashSet<?> objList1, HashSet<?> objList2) {
		HashSet<?> objSet1 = objList1;
		HashSet<?> objSet2 = objList2;		
		if (objSet1.size() < objSet2.size()) {
			objSet1.retainAll(objSet2);
			return objSet1;
		} else {
			objSet2.retainAll(objSet1);
			return objSet2;
		}
	}	
	
	//10万条以上,插入ArrayList,ArrayList转化成HashSet,用HashSet进行Join
	public static HashSet<?> BigJoin(ArrayList<?> objList1, ArrayList<?> objList2) {
		HashSet<Object> objSet1 = new HashSet<Object>(objList1);
		HashSet<Object> objSet2 = new HashSet<Object>(objList2);		
		if (objSet1.size() < objSet2.size()) {
			objSet1.retainAll(objSet2);
			return objSet1;
		} else {
			objSet2.retainAll(objSet1);
			return objSet2;
		}
	}		
		
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {		
		HashSet<String> strSet1 = new HashSet<String>();
		HashSet<String> strSet2 = new HashSet<String>();
		
		ArrayList<String> strList1 = new ArrayList<String>();
		ArrayList<String> strList2 = new ArrayList<String>();
		long p1 = 0 , p2 = 0;
		
		HashSet<String> Result;
		int minListCount = 910000; //测试记录条数
		int maxListCount = 1010000; //测试记录条数
		
		
		long tagTime = System.currentTimeMillis();
		for (int i = 0; i < maxListCount; i++) {
			if (i < minListCount)
			strSet1.add("aaa>>" + i);
			strSet2.add("aaa>>" + (12 - i));			
		}
		p1 = System.currentTimeMillis()-tagTime;
		System.out.println("HashSet:"+ p1);
		
		tagTime = System.currentTimeMillis();		
		for (int i = 0; i < maxListCount; i++) {
			if (i < minListCount)
			strList1.add("aaa>>" + i);
			strList2.add("aaa>>" + (12 - i));
			
		}		
		p2 = System.currentTimeMillis()-tagTime;
		System.out.println("ArrayList:"+ p2);
	
		tagTime = System.currentTimeMillis();
		Result = (HashSet<String>) MidJoin(strSet1,strSet2);

		p1 += System.currentTimeMillis()-tagTime;
		System.out.println("MidJoin:"+ p1);
		
		System.out.println("交集大小:"+ Result.size());
		
		tagTime = System.currentTimeMillis();		
		Result = (HashSet<String>) BigJoin(strList1,strList2);
		
		p2 += System.currentTimeMillis()-tagTime;
		System.out.println("BigJoin:"+ p2);
		System.out.println("交集大小：" + Result.size());
								
		
		Iterator<String> iterator = Result.iterator();
		while (iterator.hasNext()) {			
			System.out.println(iterator.next());
		}					

	}
}
